//
//  NavigationViewController.m
//  LoveFreshBeen
//
//  Created by 辛路琦 on 16/6/11.
//  Copyright © 2016年 xinluqi. All rights reserved.
//

#import "NavigationViewController.h"
#import "UIBarButtonItem+State.h"

@interface NavigationViewController ()<UIGestureRecognizerDelegate>

@end

@implementation NavigationViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self.interactivePopGestureRecognizer.delegate action:@selector(handleNavigationTransition:)];
    
    [self.view addGestureRecognizer:pan];
    
    pan.delegate = self;

    // 清空滑动返回手势代理, 恢复滑动功能
    self.interactivePopGestureRecognizer.enabled = NO;

}

// 重写push方法
- (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    
    if (self.childViewControllers.count > 0) {
        // 需要在调转到非根控制器的时候隐藏tabBar
        viewController.hidesBottomBarWhenPushed = YES;
        
        // 自定义返回按钮
        viewController.navigationItem.leftBarButtonItem =
        [UIBarButtonItem barButtonItemWithNormalImage:[UIImage imageNamed:@"v2_goback"]
                                     HighlightedImage:nil
                                               target:self
                                               action:@selector(backBtnClick:)];
        
        [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"navi_normal_bg"] forBarMetrics:UIBarMetricsDefault];
        
    } else {
        [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"v2_my_avatar_bg"] forBarMetrics:UIBarMetricsDefault];

    }
    
    [super pushViewController:viewController animated:animated];
}

// 重写pop方法
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
 
    UIViewController *vc = [super popViewControllerAnimated:animated];
    
    if (self.childViewControllers.count == 1) {
        [self.navigationBar setBackgroundImage:[UIImage imageNamed:@"v2_my_avatar_bg"] forBarMetrics:UIBarMetricsDefault];
    }
    
    return vc;
}


#pragma mark - <UIGestureRecognizerDelegate>
// 是否触发手势
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 判断如果当前控制器处于子控制器的时候, 才触发手势
    return self.childViewControllers.count > 1;
}

// 返回按钮点击事件
- (void)backBtnClick:(UIButton *)btn
{
    [self popViewControllerAnimated:YES];
}

+ (void)load
{
    UINavigationBar *navBar = [UINavigationBar appearanceWhenContainedIn:self, nil];
    
    [UINavigationBar appearance];
    NSMutableDictionary *dictNavTitle = [NSMutableDictionary dictionary];
    dictNavTitle[NSFontAttributeName] = [UIFont boldSystemFontOfSize:20];
    navBar.titleTextAttributes = dictNavTitle;
    [navBar setBackgroundImage:[UIImage imageNamed:@"v2_my_avatar_bg"] forBarMetrics:UIBarMetricsDefault];
}

@end
